package com.echo.boot.design.turing.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/8/29
 * Time: 22:30
 * 观察者
 * 定义了对象的一对多依赖，让多个观察者同时监听某一个对象的主题,当主题对象发生变化时，它的所有依赖者都会收到通知
 *
 * @author Administrator
 */
public class ObserverTest {
    public static void main(String[] args) {
        Subject subject = new Subject();
        Task1 task1 = new Task1();
        Task2 task2 = new Task2();
        subject.addObserver(task1);
        subject.addObserver(task2);
        subject.notifyObserver("notify .... ");
    }
}

class Subject {
    private List<Observer> container = new ArrayList<>();

    public void addObserver(Observer observer) {
        container.add(observer);
    }

    public void removeObserver(Observer observer) {
        container.remove(observer);
    }

    public void notifyObserver(String msg) {
        for (Observer item : container) {
            item.update(msg);
        }
    }

}

interface Observer {
    void update(String msg);
}

class Task1 implements Observer {

    @Override
    public void update(String msg) {
        System.out.println(" task1 ...");
    }
}

class Task2 implements Observer {

    @Override
    public void update(String msg) {
        System.out.println(" task2 .....");
    }
}
